<script setup lang="ts">
import {
  DArrowRight,
  Delete,
  Edit,
} from '@element-plus/icons-vue'
import type { Action } from 'element-plus'
import { FormModal, SearchForm } from './components'
import {
  defaultFormData,
  defaultPagingParams,
} from './index'
import type {
  DictionaryEncoInfo,
  EliminateEquipmentInfo,
  EliminateEquipmentSaveOrUpdateParams,
  TableColumn,
} from '@/types'
import {
  eliminateEquipmentApi,
  sysDictionaryEncoApi,
} from '@/api'
// ------------------use------------------
// #region
const { globalProperties, $confirm, $message }
  = useCurrentInstance()
const { withLoading, loading, vLoading }
  = useDefineLoading()
const [tableData, setTableData] = useState<any[]>([])
const [formData, setFormData] = useState<any>({
  ...defaultFormData,
})
const [total, setTotal] = useState<number>(0)
const [formModalTitle, setFormModalTitle]
  = useState<string>('')
const [catalogList, setCatalogList] = useState<
  DictionaryEncoInfo[]
>([])
const [selectCatalog, setSelectCatalog] = useState('')
// #endregion
// ------------------静态变量------------------
// #region
const columns: TableColumn<EliminateEquipmentInfo>[] = [
  {
    key: uuid(),
    width: '80',
    label: '序号',
    prop: 'number',
  },
  {
    key: uuid(),
    label: '名称',
    prop: 'equipmentName',
  },
  {
    key: uuid(),
    label: '设备型号',
    prop: 'equipmentModel',
  },
  {
    key: uuid(),
    label: '设备功率（kw）',
    prop: 'equipmentPower',
  },
  {
    key: uuid(),
    label: '淘汰理由',
    prop: 'eliminateReason',
  },
  {
    key: uuid(),
    label: '备注',
    prop: 'remarks',
  },
]
// #endregion
// ------------------动态变量------------------
// #region

// #endregion
// ------------------ref-----------
// #region
const modalRef = ref<InstanceType<typeof FormModal>>()
const pagingParams = ref({
  ...defaultPagingParams,
})
// #endregion
// ------------------reactive------
// #region

// #endregion
// ------------------computed------
// #region
// #endregion
// ------------------生命周期------------------
// #region
onMounted(async () => {
  await getCatalogList()
  getTableData()
})
// #endregion
// ------------------内置方法---------------------
// #region

// #endregion
// ------------------方法---------------------
// #region
async function getCatalogList() {
  const { data: res } = await withLoading(
    sysDictionaryEncoApi.queryList,
    'tree',
  )('TAO_TAI_PI_CI')
  setCatalogList(res)
  if (res.length > 0)
    setSelectCatalog(res[0]!.dicKey)
}
function switchCatalog(key: string) {
  setSelectCatalog(key)
  getTableData()
}
async function deleteData(id: number) {
  const res: Action = await $confirm(
    '该操作将永久删除该数据，确定删除？',
    '警告',
    {
      type: 'warning',
    },
  ).catch(e => e)

  if (res !== 'confirm')
    return
  await eliminateEquipmentApi.deleteById(id)
  globalProperties.$message.success('删除成功！')
  getTableData()
}
async function showEditDialog(row: any) {
  modalRef.value?.open()
  await nextTick()
  setFormModalTitle('编辑')
  setFormData({ ...defaultFormData, ...row })
}
async function showAddDialog() {
  modalRef.value?.open()
  await nextTick()
  setFormModalTitle('新增')
  setFormData({
    ...defaultFormData,
    batch: selectCatalog.value,
  })
}
async function getTableData() {
  const { data: res } = await withLoading(
    eliminateEquipmentApi.queryList,
  )({
    ...pagingParams.value,
    batch: +selectCatalog.value,
  })
  const { total, records } = res
  setTotal(total)
  setTableData(records)
}
async function addOrUpdateData(row: Partial<EliminateEquipmentSaveOrUpdateParams>) {
  const params = { ...row }
  await eliminateEquipmentApi.saveOrUpdate(params)
  setSelectCatalog(String(params.batch!))
  getTableData()
  modalRef.value?.close()
  $message.success('保存成功！')
}

// #endregion
</script>

<template>
  <div class="padding-sm flex gap-sm container">
    <b-scrollbar
      v-loading="{
        space: 'tree',
      }"
      class="container-left panel height-fill padding-sm box-border"
    >
      <div
        class="panel-header width-fill align-center margin-bottom-sm flex"
      >
        <h5 class="margin-0 margin-right-auto">
          淘汰批次
        </h5>
        <el-button
          link
          type="primary"
          @click="
            $router.push({
              path: '/dictionary-management',
              query: { dicCode: 'TAO_TAI_PI_CI' },
            })
          "
        >
          管理
          <el-icon><DArrowRight /></el-icon>
        </el-button>
      </div>
      <ul class="panel-list">
        <li
          v-for="item in catalogList"
          :key="item.id"
          :class="[
            {
              active: selectCatalog === item.dicKey,
            },
          ]"
          @click="switchCatalog(item.dicKey)"
        >
          {{ item.dicValue }}
        </li>
      </ul>
    </b-scrollbar>
    <div
      class="flex-direction overflow flex-fillRemaining height-fill flex align-end"
    >
      <view-table
        :loading="loading"
        :columns="columns"
        :data="tableData"
      >
        <template #actions>
          <SearchForm
            v-model="pagingParams"
            @search="getTableData"
            @reset="getTableData"
            @plus="showAddDialog"
          />
        </template>
        <template #operate="{ row }">
          <TdButton
            title="编辑"
            :icon="Edit"
            type="primary"
            @click="showEditDialog(row)"
          />
          <el-divider direction="vertical" />
          <TdButton
            title="删除"
            :icon="Delete"
            type="danger"
            @click="deleteData(row.id)"
          />
        </template>
      </view-table>
      <!-- 分页 -->
      <ListsPagination
        v-model:page-num="pagingParams.pageNumber"
        v-model:page-size="pagingParams.pageSize"
        :total="total"
        @current-change="getTableData"
        @size-change="getTableData"
      />
    </div>

    <FormModal
      ref="modalRef"
      v-model:data="formData"
      :title="formModalTitle"
      :catalog-list="catalogList"
      @save-success="addOrUpdateData(formData)"
    />
  </div>
</template>

<style lang="scss" scoped>
//------------------组件样式------------------
//-------------样式穿透-------------
</style>
